package com.dingreading.cloud.admin.util.bean;

import com.dingreading.cloud.admin.dto.ComboGoodsTypeDto;
import com.dingreading.cloud.admin.dto.GoodsCategoryDto;
import com.dingreading.cloud.admin.dto.GoodsTypeComboDto;
import com.dingreading.cloud.admin.entity.Goods;
import com.dingreading.cloud.admin.entity.GoodsCategoryLog;
import com.dingreading.cloud.admin.entity.GoodsImg;
import com.dingreading.cloud.admin.entity.GoodsUnit;
import com.dingreading.cloud.admin.service.*;
import com.dingreading.cloud.common.util.AccountUtil;
import com.dingreading.cloud.common.util.DoubleUtil;
import com.dingreading.cloud.common.util.NepUtil;
import com.dingreading.cloud.common.util.aliyun.OSSClientUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.util.*;

@RefreshScope
@Component
public class GoodsV3Util {

    public static GoodsV3Util util;

    @PostConstruct
    public void init() {
        util = this;
    }

    @Value("${envi}")
    private String envi;

    @Resource
    private GoodsSuppliersService goodsSuppliersService;
    @Resource
    private WhPurchaseGoodsService whPurchaseGoodsService;
    @Resource
    private GoodsGivesService goodsGivesService;
    @Resource
    private GoodsTypeComboService goodsTypeComboService;
    @Resource
    private ShopCartService shopCartService;
    @Resource
    protected GoodsCategoryLogService goodsCategoryLogService;

    /**
     * 新建商品数据
     */
    public static Goods newGoods(
            Goods goods, String headStaffUid, String headStaffName, String name, String intro, String details, Integer minBuyNum,
            Integer minBuyCnt, Integer buyTimes, Double price, String categoryIds, String categoryNames, String img,
            Integer hotStatus, Integer couponStatus, Integer enabled, Integer realStatus,
            Integer paymentMethod, Long freeDeliveryId
    ) {
        if (goods.getId() == null || goods.getId() <= 0) {
            goods.setEnabled(1);
            goods.setAddStaffUid(headStaffUid);
            goods.setAddStaffName(headStaffName);
        }

        if (null != name)
            goods.setName(name);
        if (null != intro)
            goods.setIntro(intro);
        if (null != details)
            goods.setDetails(details);
        if (null != categoryIds)
            goods.setCategoryIds("," + categoryIds + ",");
        if (null != categoryNames)
            goods.setCategoryNames(categoryNames);
        if (null != img)
            goods.setImg(img);
        if (null != minBuyNum)
            goods.setMinBuyNum(minBuyNum);
        if (null != minBuyCnt)
            goods.setMinBuyCnt(minBuyCnt);
        if (null != buyTimes)
            goods.setBuyTimes(buyTimes);
        if (null != price)
            goods.setPrice(price);
        if (null != hotStatus)
            goods.setHotStatus(hotStatus);
        if (null != couponStatus)
            goods.setCouponStatus(couponStatus);
        if (null != enabled)
            goods.setEnabled(enabled);
        if (null != realStatus)
            goods.setRealStatus(realStatus);
        if (null != paymentMethod)
            goods.setPaymentMethod(paymentMethod);
        if (null != freeDeliveryId)
            goods.setFreeDeliveryId(freeDeliveryId);
        goods.setLastStaffUid(headStaffUid);
        goods.setLastStaffName(headStaffName);
        return goods;
    }

    /**
     * 新建商品单位
     */
    public static GoodsUnit newGoodsUnit(Date time, GoodsUnit data, String name, Integer enabled) {
        if (data.getId() != null && data.getId() > 0) {
        } else {
            data.setEnabled(1);
        }

        if (name != null)
            data.setName(name);
        if (enabled != null)
            data.setEnabled(enabled);
        return data;
    }

    /**
     * 新建商品图集合
     */
    public static void newGoodsImgs(List<GoodsImg> list, Long goodId) {
        for (int i = 0; i < list.size(); i++) {
            GoodsImg img = list.get(i);
            img.setOrderNum(i + 1);
            img.setGoodsId(goodId);
        }
    }

    /**
     * 新建商品种类集合，并设置商品种类的序号和
     */
    public static void newCategoryLogs(List<GoodsCategoryLog> list, Long goodId) {
        for (GoodsCategoryLog categoryLog : list) {
            categoryLog.setGoodsId(goodId);
            int maxOrderNum = util.goodsCategoryLogService.getMaxOrderNum(categoryLog.getCategoryId()) + 1;
            categoryLog.setOrderNum(maxOrderNum);
        }
    }

    /**
     * 获取种类的id与名称
     */
    public static GoodsCategoryDto getCategoryIdsAndNames(List<GoodsCategoryLog> categoryLogList) {
        String categoryIds = "";
        String categoryNames = "";
        // 获取分类的最大序号
        for (int i = 0; i < categoryLogList.size(); i++) {
            GoodsCategoryLog categoryLog = categoryLogList.get(i);

            Long categoryId = categoryLog.getCategoryId();
            String categoryName = categoryLog.getCategoryName();
            categoryIds += categoryId;
            categoryNames += categoryName;
            if (i != categoryLogList.size() - 1) {
                categoryIds += ",";
                categoryNames += ",";
            }
        }

        GoodsCategoryDto dto = new GoodsCategoryDto();
        dto.setCategoryIds(categoryIds);
        dto.setCategoryNames(categoryNames);
        return dto;
    }

    /**
     * 获取种类的id与名称
     */
    public static GoodsCategoryDto setCategoryIdsAndNamesAndIdsAndNewList(List<GoodsCategoryLog> categoryLogList, Long goodsId) {
        String categoryIds = "";
        String categoryNames = "";
        List<Long> categoryLogIds = new ArrayList<>();
        List<GoodsCategoryLog> newCategoryList = new ArrayList<>();

        // 获取分类的最大序号
        for (int i = 0; i < categoryLogList.size(); i++) {
            GoodsCategoryLog goodsCategoryLog = categoryLogList.get(i);
            Long categoryLogId = goodsCategoryLog.getId();
            Long categoryId = goodsCategoryLog.getCategoryId();
            String categoryName = goodsCategoryLog.getCategoryName();

            categoryIds += categoryId;
            categoryNames += categoryName;
            if (i != categoryLogList.size() - 1) {
                categoryIds += ",";
                categoryNames += ",";
            }

            if (null == categoryLogId || categoryLogId <= 0) {
                GoodsCategoryLog categoryLog = new GoodsCategoryLog();
                int maxOrderNum = util.goodsCategoryLogService.getMaxOrderNum(categoryId) + 1;
                categoryLog.setGoodsId(goodsId);
                categoryLog.setCategoryId(categoryId);
                categoryLog.setCategoryName(categoryName);
                categoryLog.setOrderNum(maxOrderNum);
                newCategoryList.add(categoryLog);
            } else {
                categoryLogIds.add(categoryLogId);
            }
        }

        GoodsCategoryDto dto = new GoodsCategoryDto();
        dto.setCategoryIds(categoryIds);
        dto.setCategoryNames(categoryNames);
        dto.setCategoryLogIds(categoryLogIds);
        dto.setNewCategoryList(newCategoryList);
        return dto;
    }

    /**
     * 获取商品要删除的封面图片和商品详情内的图片
     */
    public static List<String> getDeleteImgAndDetails(Goods goods, String goodsImg, String goodsDetails) {
        List<String> ossFileUrls = new ArrayList<>();
        // 获取将要删除的封面图的阿里云文件路径
        if (!goods.getImg().equals(goodsImg))
            ossFileUrls.add(getOssFileUrl(goods.getImg()));

        // 获取将要删除的封商品详情（富文本）的阿里云文件路径
        String exDetails = goods.getDetails();
        if (StringUtils.isNotBlank(exDetails)) {
            if (StringUtils.isBlank(goodsDetails)) {
                // 删除原商品详情全部的图片
                String[] exDetailsOssFileUrls = getDetailsOssFileUrls(exDetails);
                if (null != exDetailsOssFileUrls && exDetailsOssFileUrls.length > 0) {
                    ossFileUrls.addAll(Arrays.asList(exDetailsOssFileUrls));
                }
            } else {
                if (!exDetails.equals(goodsDetails)) {
                    // 删除原商品详情里和新商品详情里不同的图片
                    String[] exDetailsOssFileUrls = getDetailsOssFileUrls(exDetails);
                    // 判断原商品详情是否有阿里云图片
                    if (null != exDetailsOssFileUrls && exDetailsOssFileUrls.length > 0) {
                        String[] detailsOssFileUrls = getDetailsOssFileUrls(goodsDetails);
                        if (null != detailsOssFileUrls && detailsOssFileUrls.length > 0) {
                            // 新商品详情有阿里云图片，查出需要删除的阿里云图片
                            String[] exDetailsOssFileUrlList = exDetailsOssFileUrls;
                            List<String> detailsOssFileUrlList = Arrays.asList(detailsOssFileUrls);
                            for (String exUrl : exDetailsOssFileUrlList) {
                                // 新商品详情图片不包含旧的商品详情图，则删除旧图
                                if (!detailsOssFileUrlList.contains(exUrl))
                                    ossFileUrls.add(exUrl);
                            }
                        } else {
                            // 新商品详情没有阿里云图片，删除原商品详情全部的图片
                            ossFileUrls.addAll(Arrays.asList(exDetailsOssFileUrls));
                        }
                    }
                }
            }
        }
        return ossFileUrls;
    }

    /**
     * 判断商品规格是否被使用
     */
    public static String judgeUseGoods(Long goodsId) {
        boolean b = util.goodsSuppliersService.havesGoodsId(goodsId);
        if (b)
            return "已加入供应商，不能操作";
        b = util.whPurchaseGoodsService.havesGoodsId(goodsId);
        if (b)
            return "已进行采购，不能操作";
        b = util.goodsGivesService.haveGoodsId(goodsId);
        if (b)
            return "已加入赠品管理，不能操作";
        b = util.goodsTypeComboService.haveGoodsId(goodsId);
        if (b)
            return "已加入商品组合，不能操作";
        b = util.shopCartService.haveGoodsId(goodsId);
        if (b)
            return "已加入购物车，不能操作";

        return "";
    }

    /**
     * 判断商品规格是否被使用
     */
    public static String judgeUseGoodsType(Long goodsTypeId) {
        boolean b = util.goodsSuppliersService.havesGoodsTypeId(goodsTypeId);
        if (b)
            return "已加入供应商，不能操作";
        b = util.whPurchaseGoodsService.havesGoodsTypeId(goodsTypeId);
        if (b)
            return "已进行采购，不能操作";

        b = util.goodsGivesService.haveByProductId(2, goodsTypeId);
        if (b)
            return "已被加入赠品管理，不能操作";

        b = util.goodsTypeComboService.havesGoodsTypeIds(goodsTypeId);
        if (b)
            return "已加入商品组合，不能操作";

        b = util.shopCartService.haveGoodsTypeId(goodsTypeId);
        if (b)
            return "已加入购物车，不能操作";
        return "";
    }

    /**
     * 获取商品图片的阿里云文件存储地址
     */
    public static String getOssFileUrl(String imgUrl) {
        String baseUrl = "https://dingreading.oss-cn-shanghai.aliyuncs.com/";
        return StringUtils.substringAfterLast(imgUrl, baseUrl);
    }

    /**
     * 获取商品富文本内的阿里云文件存储地址
     */
    public static String[] getDetailsOssFileUrls(String details) {
        String[] strings = StringUtils.substringsBetween(details, "<img src=\"https://dingreading.oss-cn-shanghai.aliyuncs.com/", "\"");
        return strings;
    }

    /**
     * 删除阿里云上存储的文件
     */
    public static void deleteOssFiles(List<String> fileUrls) {
        // 生产环境且阿里云文件地址不为空，才能删除
        if (AccountUtil.judgeProd(util.envi) && CollectionUtils.isNotEmpty(fileUrls)) {
            // 删除阿里云图片
            OSSClientUtil ossClientUtil = new OSSClientUtil();
            ossClientUtil.initOss();
            ossClientUtil.deleteFiles(OSSClientUtil.publicBucket, fileUrls);
        }
    }


    /**
     * 获取组合商品的最低可售数量和总重量
     */
    public static ComboGoodsTypeDto getComboGoodsTypeDto(List<GoodsTypeComboDto> comboDtoList, Map<Long, Integer> stockNumMap, Map<Long, Integer> waitSendNumMap) {
        ComboGoodsTypeDto dto = new ComboGoodsTypeDto();
        if (CollectionUtils.isNotEmpty(comboDtoList)) {
            // 组合商品总重量
            double weight = 0;
            // 组合商品的最低可售数量集合
            Set<Integer> minBuyNumList = new HashSet<>();

            for (GoodsTypeComboDto comboDto : comboDtoList) {
                int stockNum = OrderFormV3Util.getGoodsTypeNum(stockNumMap.get(comboDto.getGoodsTypeId()), waitSendNumMap.get(comboDto.getGoodsTypeId()));
                // 套装内子商品的库存可售数量
                comboDto.setStockNum(stockNum);
                // 组合商品的最低可售数量=库存数量除以商品可购买数
                if (!minBuyNumList.contains(0))
                    minBuyNumList.add(stockNum / comboDto.getNum());
                //  组合商品重量
                weight = DoubleUtil.sum(weight, DoubleUtil.mul(comboDto.getNum(), NepUtil.nullToZero(comboDto.getWeight())));
            }

            // 获取最低可售数量
            if (CollectionUtils.isNotEmpty(minBuyNumList))
                dto.setSaleNum(Collections.min(minBuyNumList));
            else
                dto.setSaleNum(0);
            dto.setWeight(weight);
        }
        return dto;
    }

}
